package com.cindata

import com.cindata.dictionary.*
import grails.gorm.transactions.Transactional
import grails.converters.JSON

import java.security.MessageDigest
import java.text.SimpleDateFormat

import com.cindata.dictionary.*

@Transactional
class AccountService
{

    static scope = "singleton"

    def workflowInstanceService

    // 递归查出所有上级机构
    def getAllParent(Account account, List accountList)
    {
        accountList.add(account)
        if (!account?.parent)
        {
            return accountList
        }
        else
        {
            getAllParent(account?.parent, accountList)
        }
    }

    def accountInserts(List<Map> accountMapList)
    {
        def AccountLevelArr = AccountLevelDict.all
        def AccountArr = Account.all
        def ProvinceArr = Province.all
        def CityArr = City.all
        def DistrictArr = District.all

        accountMapList.each { Map param ->

            AccountArr = Account.all

            param.level = param.level ? AccountLevelArr.find { it.name == param.level } : null
            param.parent = param.parent ? AccountArr.find { it.name == param.parent } : null
            param.province = param.province ? ProvinceArr.find { it.name == param.province } : null
            param.city = param.city ? CityArr.find { it.name == param.city } : null
            param.district = param.district ? DistrictArr.find { it.name == param.district } : null

            def account = new Account(param)
            if (account.validate())
            {
                account.save flush: true

                // 递归查出所有上级机构（包括自己）
                def accountList = getAllParent(account, [])
                accountList?.each {
                    def accountManageAccount = new AccountManageAccount()
                    accountManageAccount.account = it
                    accountManageAccount.manageAccount = account
                    accountManageAccount.save()
                }
            }
            else
            {
                println account.errors
            }
        }
        return
    }

    // 初始化机构登记流程
    def initAccountFlowStage(Account account, Workflow workflow)
    {

        def workflowInstance = WorkflowInstance.find("from WorkflowInstance where account.id = ? and workflow.id = ? and status.name = ?",[account.id,workflow.id,'Pending'])
        if(!workflowInstance){
            workflowInstance = new WorkflowInstance()
        }else{
            println "该工作流已初始化过"
            return
        }
        workflowInstance.workflow = workflow
        workflowInstance.account = account
        workflowInstance.name = workflow.name+new Date()
        if (workflowInstance.validate())
        {
            workflowInstance.save flush: true
        }
        else
        {
            println workflowInstance.errors
        }

        workflowInstanceService.initWorkflowInstance(workflowInstance)

//        def flowFirstStage = WorkflowStage.find("from WorkflowStage where workflow.id = ? order by executionSequence asc", [workflow?.id])
//        def workflowInstanceStage = WorkflowInstanceStage.find("from WorkflowInstanceStage where account.id = ? and stage.id = ? order by executionSequence asc", [account?.id, flowFirstStage?.stage?.id])
//        if (workflowInstanceStage)
//        {
//            workflowInstanceStage.startTime = new Date()
//            workflowInstanceStage.save flush: true
//
//            account.workflow = workflow
//            account.isInWorkflow = true
//            account.save flush: true
//        }
    }

//    // 推进
//    def approve(Account account)
//    {
//        def map = [:]
//
//        def currentFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and stage.id = ? order by executionSequence asc", [account?.id, account?.stage?.id])
//
//        // 事件
//        accountFlowStageEventService.evaluate(currentFlowStage, "negative")
//
//        // 验证
//        def verifyCondition = accountFlowStageConditionService.evaluate(account)
//        if (!verifyCondition['flag'])
//        {
//            return verifyCondition
//        }
//
//        // 事件
//        accountFlowStageEventService.evaluate(currentFlowStage, "positive")
//
//        def nextFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and executionSequence > ? order by executionSequence asc", [account?.id, currentFlowStage?.executionSequence])
//        if (!nextFlowStage)
//        {
//            map['flag'] = false
//            map['message'] = "找不到工作流"
//            return map
//        }
//
//        // 如果 nextFlowStage 为工作流的最后一个阶段，则将 nextFlowStage endTime 赋值成当前时间,将机构状态赋值成 Completed
//        def lastFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and executionSequence > ? order by executionSequence asc", [account?.id, nextFlowStage?.executionSequence])
//
//        currentFlowStage.endTime = new Date()
//        currentFlowStage.processed = true
//        currentFlowStage.save flush: true
//
//        nextFlowStage.startTime = new Date()
//        if (!lastFlowStage)
//        {
//            nextFlowStage.endTime = new Date()
//            account.workflowStatus = "Completed"
//            account.isInWorkflow = false
//        }
//        nextFlowStage.save flush: true
//
//        account.stage = (AccountStage) nextFlowStage?.stage
//        account.save flush: true
//
//        // 短信
//        // accountFlowStageNotificationService.sendNotification(account)
//
//        map['flag'] = true
//        map['message'] = "成功"
//        return map
//    }
//
//    // 拒绝
//    Boolean reject(Account account)
//    {
//        def flag = false
//        def currentFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and stage.id = ? order by executionSequence asc", [account?.id, account?.stage?.id])
//        if (currentFlowStage?.canReject)
//        {
//            def previousFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and executionSequence < ? and processed = true order by executionSequence desc", [account?.id, currentFlowStage?.executionSequence])
//            if (previousFlowStage)
//            {
//                account.stage = AccountStage.find("from AccountStage where id = ?", [previousFlowStage?.stage?.id])
//                if (account.validate())
//                {
//                    account.save flush: true
//
//                    //发送消息
//                    // accountFlowStageNotificationService.sendNotification(account)
//
//                    flag = true
//                }
//                else
//                {
//                    account.errors.each
//                    {
//                        log.info "${it}"
//                    }
//                }
//            }
//        }
//        flag
//    }
}
